package com.example.installtest.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 静默安装的实现类,调用install()方法执行具体的静默安装逻辑
 */

public class SilentInstall {
    private static String TAG="SlientInstall";

    public boolean install(String apkPath){
        boolean result=false;
        DataOutputStream dataOutputStream=null;
        BufferedReader errorStream=null;
        try{
            //申请su权限
            Process process=Runtime.getRuntime().exec("su");
            //执行pm install 命令
            String command="pm install -r"+apkPath+"\n";
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream=new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg="";
            String line;
            while((line=errorStream.readLine())!=null){
                msg+=line;
            }
            Log.d(TAG, "install: "+msg);
            //如果执行结果中包含Failure字样就认为是安装失败,否则安装成功
            if(!msg.contains("Failure")){
                result=true;
            }
        } catch (Exception e) {
            Log.d(TAG, "install: "+e.getMessage(),e);
            e.printStackTrace();
        } finally {
            try {
                if(dataOutputStream!=null){
                    dataOutputStream.close();
                }
                if(errorStream!=null){
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
